import type { EChartsOption } from 'echarts'

// 简易格式化工具
const formatCurrency = (n: number) => {
  const v = Number(n) || 0
  if (v >= 10000) return `¥${(v / 10000).toFixed(2)}万`
  return `¥${v.toLocaleString('zh-CN')}`
}
const formatQuantity = (n: number) => {
  const v = Number(n) || 0
  return `${v.toLocaleString('zh-CN')}斤`
}
const truncateLabel = (s: string, max = 8) => (s && s.length > max ? `${s.slice(0, max)}…` : s)

// 月度折线图（12个月）
export function useResponsiveLineForYear(
  data: Array<{ month: string; value: number }>,
): EChartsOption {
  const months = data.map(d => d.month)
  const values = data.map(d => d.value ?? 0)
  const screenWidth = typeof window !== 'undefined' ? window.innerWidth : 1024
  const isMobile = screenWidth <= 768

  const option: EChartsOption = {
    color: ['#2563eb'],
    grid: isMobile ? { top: 28, right: 16, bottom: 50, left: 48 } : { top: 36, right: 24, bottom: 36, left: 56 },
    animationDuration: 600,
    animationEasing: 'cubicOut',
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'line' },
      formatter: (params: any) => {
        const p = Array.isArray(params) ? params[0] : params
        const val = Number(p?.value ?? 0)
        return `${p?.axisValue}<br/>金额：${formatCurrency(val)}`
      },
    },
    xAxis: {
      type: 'category',
      data: months,
      axisTick: { alignWithLabel: true },
      axisLabel: { interval: 0, rotate: isMobile ? 25 : 0, fontSize: 11 },
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: (val: number) => formatCurrency(val),
      },
    },
    series: [
      {
        name: '金额',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: { width: 3 },
        areaStyle: { opacity: 0.18, color: 'rgba(37, 99, 235, 0.18)' },
        emphasis: { focus: 'series' },
        data: values,
      },
    ],
  }

  return option
}

// 车辆类别折线图
export function useResponsiveLineForVehicles(
  data: Array<{ name: string; value: number }>,
): EChartsOption {
  const categories = data.map(d => d.name)
  const values = data.map(d => d.value ?? 0)
  const screenWidth = typeof window !== 'undefined' ? window.innerWidth : 1024
  const isMobile = screenWidth <= 768

  const option: EChartsOption = {
    color: ['#22c55e'],
    grid: isMobile ? { top: 28, right: 16, bottom: 56, left: 48 } : { top: 36, right: 24, bottom: 36, left: 56 },
    animationDuration: 600,
    animationEasing: 'cubicOut',
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'line' },
      formatter: (params: any) => {
        const p = Array.isArray(params) ? params[0] : params
        const val = Number(p?.value ?? 0)
        return `${p?.axisValue}<br/>金额：${formatCurrency(val)}`
      },
    },
    xAxis: {
      type: 'category',
      data: categories,
      axisTick: { alignWithLabel: true },
      axisLabel: {
        interval: 0,
        rotate: isMobile ? 28 : (categories.length > 8 ? 30 : 0),
        fontSize: 11,
        formatter: (val: string) => truncateLabel(val, isMobile ? 8 : 10),
      },
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: (val: number) => formatCurrency(val),
      },
    },
    series: [
      {
        name: '金额',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: { width: 3 },
        areaStyle: { opacity: 0.18, color: 'rgba(34, 197, 94, 0.18)' },
        emphasis: { focus: 'series' },
        data: values,
      },
    ],
  }

  return option
}

// 客户维度金额/斤数双柱图
export function useResponsiveBarForCustomers(
  data: Array<{ name: string; amount: number; quantity: number }>,
): EChartsOption {
  const categories = data.map(d => d.name)
  const amounts = data.map(d => d.amount ?? 0)
  const quantities = data.map(d => d.quantity ?? 0)

  // 屏幕宽度判断：移动端使用横向条形图
  const screenWidth = typeof window !== 'undefined' ? window.innerWidth : 1024
  const isMobile = screenWidth <= 768

  const categoryCount = categories.length

  if (isMobile) {
    // 移动端横向条形图，避免x轴拥挤
    const labelMaxLength = categoryCount > 12 ? 6 : categoryCount > 8 ? 8 : 10

    const option: EChartsOption = {
      color: ['#f59e0b', '#6366f1'],
      grid: { top: 28, right: 16, bottom: 24, left: 80 },
      animationDuration: 600,
      animationEasing: 'cubicOut',
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' },
        formatter: (params: any[]) => {
          const axis = (params && params[0]?.axisValue) || ''
          const content = params
            .map(p => {
              const isAmount = p?.seriesName === '金额'
              const val = Number(p?.value ?? 0)
              return `${p?.marker}${p?.seriesName}：${isAmount ? formatCurrency(val) : formatQuantity(val)}`
            })
            .join('<br/>')
          return `${axis}<br/>${content}`
        },
      },
      legend: { bottom: 2, left: 'center', data: ['金额', '斤数'] },
      xAxis: {
        type: 'value',
        axisLabel: { formatter: (val: number) => formatCurrency(val), fontSize: 11 },
      },
      yAxis: {
        type: 'category',
        data: categories,
        axisTick: { alignWithLabel: true },
        axisLabel: {
          interval: 0,
          fontSize: 11,
          margin: 8,
          formatter: (val: string) => truncateLabel(val, labelMaxLength),
        },
      },
      dataZoom: categoryCount > 10 ? [
        { type: 'inside', yAxisIndex: 0, filterMode: 'weakFilter' },
      ] : undefined,
      series: [
        {
          name: '金额',
          type: 'bar',
          barMaxWidth: 18,
          itemStyle: { borderRadius: [0, 4, 4, 0] },
          emphasis: { focus: 'series' },
          label: { show: true, position: 'right', fontSize: 11, formatter: (p: any) => formatCurrency(Number(p.value || 0)) },
          data: amounts,
        },
        {
          name: '斤数',
          type: 'bar',
          barMaxWidth: 18,
          itemStyle: { borderRadius: [0, 4, 4, 0] },
          emphasis: { focus: 'series' },
          label: { show: true, position: 'right', fontSize: 11, formatter: (p: any) => formatQuantity(Number(p.value || 0)) },
          data: quantities,
        },
      ],
    }

    return option
  }

  // 桌面端：保持纵向柱状图不变，并在大量类别时优化标签显示
  const shouldRotate = categoryCount > 4
  const rotateAngle = categoryCount > 8 ? 45 : categoryCount > 6 ? 35 : 25
  const bottomSpace = shouldRotate ? (categoryCount > 8 ? 60 : 50) : 36
  const labelMaxLength = categoryCount > 8 ? 6 : categoryCount > 6 ? 8 : 10

  const option: EChartsOption = {
    color: ['#f59e0b', '#6366f1'],
    grid: { top: 42, right: 24, bottom: bottomSpace, left: 64 },
    animationDuration: 600,
    animationEasing: 'cubicOut',
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: (params: any[]) => {
        const axis = (params && params[0]?.axisValue) || ''
        const content = params
          .map(p => {
            const isAmount = p?.seriesName === '金额'
            const val = Number(p?.value ?? 0)
            return `${p?.marker}${p?.seriesName}：${isAmount ? formatCurrency(val) : formatQuantity(val)}`
          })
          .join('<br/>')
        return `${axis}<br/>${content}`
      },
    },
    legend: { top: 6, right: 8, data: ['金额', '斤数'] },
    xAxis: {
      type: 'category',
      data: categories,
      axisTick: { alignWithLabel: true },
      axisLabel: {
        interval: categoryCount > 12 ? 'auto' : 0,
        rotate: shouldRotate ? rotateAngle : 0,
        fontSize: 11,
        margin: shouldRotate ? 8 : 6,
        formatter: (val: string) => truncateLabel(val, labelMaxLength),
      },
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: (val: number) => formatCurrency(val),
      },
    },
    series: [
      {
        name: '金额',
        type: 'bar',
        barMaxWidth: categoryCount > 10 ? 20 : 28,
        itemStyle: { borderRadius: [4, 4, 0, 0] },
        emphasis: { focus: 'series' },
        data: amounts,
      },
      {
        name: '斤数',
        type: 'bar',
        barMaxWidth: categoryCount > 10 ? 20 : 28,
        itemStyle: { borderRadius: [4, 4, 0, 0] },
        emphasis: { focus: 'series' },
        data: quantities,
      },
    ],
  }

  return option
}